import React, { Component } from "react";
import QueueAnim from "rc-queue-anim";
import { connect } from "dva";
import { Table, Modal, message } from "antd";
import TagSelect from "@/components/TagSelect/TagSelect";
import ContentTab from "../../components/DetailTabs/ContentTab";
import { releaseDrafcheck, getReleaseDraftList, getContentDetailsOther, getDetailesStatisticalData, pushSiteList } from "../../services/services";
import CustomModal from "@/components/CustomModal/index";

import { judgeMonCode, handleMonTextForNewsList } from '@/utils/formatMonTextStyle.js'

const { confirm } = Modal;
@connect(({ add }) => ({ add }))
class ReleaseDraft extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageSize: 10, //表格数据当前页显示条数
      total: 0, //表格数据总条数
      currentPage: 1, //表格数据当前页码
      category: "文章", //分类名称
      categoryId: 1, //分类id
      create_time: "1970-01-01 00:00:00", //初始查询全部时间
      keyword: "", //搜索关键词
      searchType: 1, //搜索类型
      tableLoading: false, //表格加载效果
      tableData: [], //列表表格数据
      showDetailVariable: true, //显示详情页变量
      tabKey: "1", //详情tab页索引
      detailsContent: null, //详情
      statisticalData: [], //统计数据
      timer_info: "全部",
      customModalVisible: false,
      pushSiteList: []
    };
  }
  componentDidMount() {
    this.getTableData();
  }

  // 类别切换
  categoryChange = data => {
    this.setState(
      {
        tableLoading: true,
        keyword: "",
        category: data.category_name,
        categoryId: data.category_id
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 时间选择切换
  selectedTimeChange = (timer, doc) => {
    this.setState(
      {
        tableLoading: true,
        create_time: timer,
        timer_info: doc
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 搜索
  handleSeachButton = data => {
    this.setState(
      {
        tableLoading: true,
        categoryId: data.category_id,
        keyword: data.searchKeyword,
        searchType: data.searchType,
        category: data.category_name
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 获取表格数据
  getTableData = () => {
    this.setState({
      tableLoading: true
    });
    const { categoryId, currentPage, searchType, pageSize, create_time, keyword } = this.state;
    const params = {
      content_type: categoryId,
      create_time: create_time,
      keyword: keyword,
      search_type: searchType,
      page: currentPage,
      per_page: pageSize
    };
    getReleaseDraftList(params)
      .then(res => {
        if (res.code === 200) {
          const result = res.data;
          this.setState({
            tableLoading: false,
            total: result.total,
            currentPage: result.current_page,
            pageSize: result.per_page,
            tableData: result.data
          });
        } else if (res.code === 500) {
          this.setState({
            tableLoading: false
          });
          console.log(res.msg);
        } else {
          this.setState({
            tableLoading: false
          });
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 表格显示条数切换
  pageSizeChange = (current, size) => {
    this.setState(
      {
        pageSize: size,
        currentPage: current
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 当前页面变化
  currentPageChange = (page, pageSize) => {
    this.setState(
      {
        currentPage: page
      },
      () => {
        this.getTableData();
      }
    );
  };
  // 跳转至详情
  showDetailChange = row => {
    this.setState(
      {
        showDetailVariable: false
      },
      () => {
        this.getDetailsData(row);
        this.getStatistical(row);
      }
    );
  };
  // 获取内容详情数据
  getDetailsData = row => {
    const params = {
      id: row.id
    };
    getContentDetailsOther(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            detailsContent: res.data || {}
          });
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  // 通过按钮警告框
  showPassConfirm = row => {
    let that = this;
    const status = () => {
      if (this.props.add.rightList.includes("/pushStatusThree")) {
        return 3;
      }
      if (this.props.add.rightList.includes("/pushStatusTwo")) {
        return 2;
      }
      if (this.props.add.rightList.includes("/pushStatusOne")) {
        return 1;
      }
      return 4;
    };
    confirm({
      title: "通过",
      content: "是否确认通过审核？",
      onOk() {
        const params = {
          id: row.id,
          push_status: status()
        };
        releaseDrafcheck(params)
          .then(res => {
            if (res.code === 200) {
              that.setState(
                {
                  tableLoading: false
                },
                that.getTableData()
              );
            } else if (res.code === 500) {
              that.setState({
                tableLoading: false
              });
              console.log(res.msg);
            } else {
              that.setState({
                tableLoading: false
              });
              message.error("连接失败");
            }
          })
          .catch(err => {
            console.log(err);
          });
      },
      onCancel() {
        message.warning("取消操作");
      },
      cancelText: "取消",
      okText: "确定"
    });
  };
  // 不通过按钮警告框;
  showNoPassConfirm = row => {
    let that = this;
    confirm({
      title: "不通过",
      content: "是否确认不通过审核？",
      onOk() {
        const params = {
          id: row.id,
          push_status: 4
        };
        releaseDrafcheck(params)
          .then(res => {
            if (res.code === 200) {
              that.setState(
                {
                  tableLoading: false
                },
                that.getTableData()
              );
            } else if (res.code === 500) {
              that.setState({
                tableLoading: false
              });
              console.log(res.msg);
            } else {
              that.setState({
                tableLoading: false
              });
              message.error("连接失败");
            }
          })
          .catch(err => {
            console.log(err);
          });
      },
      onCancel() {
        message.warning("取消操作");
      },
      cancelText: "取消",
      okText: "确定"
    });
  };
  // 返回上一级
  goBack = () => {
    this.setState({
      showDetailVariable: true
    });
  };

  // 获取详情统计数据
  getStatistical = row => {
    const params = {
      site_id: row.site_id,
      content_type: row.content_type,
      content_id: row.content_id,
      source: 0
    };
    getDetailesStatisticalData(params)
      .then(res => {
        if (res.code === 200) {
          let sdata = [];
          let arr = ["阅读量", "评论量", "点赞量", "分享量"];
          let arr1 = ["scan_count", "comment_count", "like_count", "share_count"];
          if (res.code) {
            for (let i = 0; i < 4; i++) {
              let obj = {};
              obj["x"] = arr[i];
              obj["y"] = res.data[arr1[i]];
              sdata.push(obj);
            }
          }
          this.setState({
            statisticalData: sdata
          });
        } else if (res.code === 500) {
          console.log(res.msg);
        } else {
          message.error("连接失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  showCustomModal = record => {
    const receive_sites = record.receive_site;
    if (!receive_sites) {
      return message.warn("暂无已推送站点");
    }
    const params = {
      id: receive_sites.join(",")
    };
    pushSiteList(params)
      .then(res => {
        if (res.code === 200) {
          this.setState({
            customModalVisible: true,
            pushSiteList: res.data
          });
        } else {
          message.error("请求失败");
        }
      })
      .catch(err => {
        console.log(err);
      });
  };
  handleCustomModalOk = () => {
    this.setState({
      customModalVisible: false
    });
  };
  handleCustomModalCancel = () => {
    this.setState({
      customModalVisible: false
    });
  };
  render() {
    const { tableData, total, tableLoading } = this.state;
    const quanxian = this.props.add.rightList ? this.props.add.rightList : [];
    const columns = [
      {
        title: "标题",
        dataIndex: "title",
        // key: "title",
        align: "center",
        render: (text, record, index) => (
          <div style={{ textAlign: "left" }}>
            {/* 判断是否符合蒙文编码 */}
            { judgeMonCode(text) ?
              handleMonTextForNewsList(tableData[index].create_time, text)
            :
            <div style={{ textAlign: "center" }}> {text} </div> 
            }
          </div>
        )
      },
      {
        title: "类型",
        dataIndex: "content_type",
        key: "content_type",
        align: "center",
        render: (text, record) => {
          if (text === 1) {
            return "文章";
          } else if (text === 2) {
            return "图集";
          } else if (text === 4) {
            return "视频";
          } else {
            return "音频";
          }
        }
      },
      {
        title: "发布站点",
        dataIndex: "site_name",
        key: "site_name",
        align: "center"
      },
      {
        title: "审核状态",
        dataIndex: "push_status",
        key: "push_status",
        align: "center",
        render: (text, record) => {
          if (text === 0) {
            return <span style={{ color: "#f9be71" }}>待审核</span>;
          } else if (text === 1) {
            return "待二审";
          } else if (text === 2) {
            return "待终审";
          } else if (text === 3) {
            return "终审通过";
          } else if (text === 4) {
            return "审核不通过";
          } else {
            return <span style={{ color: "#f9be71" }}>草稿</span>;
          }
        }
      },
      {
        title: "创建时间",
        dataIndex: "create_time",
        key: "create_time",
        align: "center"
      },
      {
        title: "操作",
        key: "action",
        align: "center",
        render: (text, record) => {
          const flag = state => {
            if (state <= 2 && quanxian.includes("/pushStatusThree")) {
              return "通过终审";
            } else if (state <= 1 && quanxian.includes("/pushStatusTwo")) {
              return "通过二审";
            } else if (state === 0 && quanxian.includes("/pushStatusOne")) {
              return "通过初审";
            } else {
              return "";
            }
          };
          let val = "";
          if (record.push_status === 0) {
            val = flag(record.push_status);
          } else if (record.push_status === 1) {
            val = flag(record.push_status);
          } else if (record.push_status === 2) {
            val = flag(record.push_status);
          }
          return (
            <div>
              {val ? (
                <span style={{ color: "#4b7902", cursor: "pointer" }} onClick={this.showPassConfirm.bind(this, record)}>
                  {val}&nbsp;&nbsp;
                </span>
              ) : null}
              {(quanxian.includes("/pushStatusOne") || quanxian.includes("/pushStatusTwo") || quanxian.includes("/pushStatusThree")) && val ? (
                <span style={{ color: "#d9001b", cursor: "pointer" }} onClick={this.showNoPassConfirm.bind(this, record)}>
                  {record.push_status === 3 || record.push_status === 4 ? "" : "不通过"}&nbsp;&nbsp;
                </span>
              ) : null}
              <span style={{ color: "#1890ff", cursor: "pointer" }} onClick={this.showDetailChange.bind(this, record)}>
                查看详情&nbsp;&nbsp;
              </span>
              {/* <span style={{ cursor: "pointer", color: "#1890ff" }} onClick={this.showCustomModal.bind(this, record)}>
                推送站点
              </span> */}
            </div>
          );
        }
      }
    ];
    // 表格分页器配置项
    const paginationProps = {
      current: this.state.currentPage,
      showSizeChanger: true,
      showQuickJumper: true,
      total: total,
      showTotal: () => `共 ${this.state.total} 条记录`,
      pageSize: this.state.pageSize,
      pageSizeOptions: ["5", "10", "20", "50"],
      onChange: this.currentPageChange,
      onShowSizeChange: this.pageSizeChange
    };
    return (
      <QueueAnim className="ReleaseDraft">
        <div key="t2" className="BasicContent">
          <div className="main">
            {this.state.showDetailVariable ? (
              <div>
                <TagSelect
                  currentCategory={[this.state.category]}
                  currentTimer={[this.state.timer_info]}
                  showAllDelVariable={false}
                  getcategoryChange={this.categoryChange}
                  getSelectedTimeChange={this.selectedTimeChange}
                  handleSeachButton={this.handleSeachButton}
                />
                <Table loading={tableLoading} rowKey={recored => recored.id} columns={columns} dataSource={tableData} bordered pagination={paginationProps} />
              </div>
            ) : (
              <div>
                {this.state.detailsContent ? (
                  <ContentTab
                    statisticalData={this.state.statisticalData}
                    parentBack={this.goBack}
                    delDetailsTable={this.state.delDetailsTable}
                    contentData={this.state.detailsContent}
                    tabKey={this.state.tabKey}
                  />
                ) : null}
              </div>
            )}
          </div>
        </div>
        <CustomModal
          customModalVisible={this.state.customModalVisible}
          handleCustomModalOk={this.handleCustomModalOk}
          handleCustomModalCancel={this.handleCustomModalCancel}
          data={this.state.pushSiteList}
        />
      </QueueAnim>
    );
  }
}

export default ReleaseDraft;
